package ar.com.cooker.dao.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import ar.com.cooker.dao.UserDao;
import ar.com.cooker.model.User;

@Repository
@Transactional
public class UserDaoImpl implements UserDao {

	private EntityManager entityManager;

	@Override
	public void delete(Integer id) {
		User u = getEntityManager().find(User.class, id);
		getEntityManager().remove(u);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<User> findAll() {
		Query q = getEntityManager().createQuery("FROM User u");
		return q.getResultList();
	}

	@Override
	public User findById(Integer id) {
		return getEntityManager().find(User.class, id);
	}

	@Override
	public void save(User t) {
		getEntityManager().persist(t);
	}

	@Override
	public void update(User t) {
		if (t.getId() == null) {
			// TODO excepcion a realizar
		} else {
			getEntityManager().merge(t);
		}
	}

	@PersistenceContext
	public void setEntityManager(EntityManager entityManager) {
		this.entityManager = entityManager;
	}

	public EntityManager getEntityManager() {
		return entityManager;
	}

}
